#include <jni.h>
#include <stdlib.h>
#include <string.h>

char *join(const char *s1, const char *s2) {

    char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the zero-terminator

    if (result == NULL) {
        return "";
    }

    strcpy(result, s1);
    strcat(result, s2);

    return result;
}

jstring convertToJstringWithUTF(JNIEnv *env, const char *source) {
    jclass strClass = (*env)->FindClass(env, "java/lang/String");
    jmethodID ctorID = (*env)->GetMethodID(env, strClass, "<init>", "([BLjava/lang/String;)V");
    jbyteArray bytes = (*env)->NewByteArray(env, strlen(source));
    (*env)->SetByteArrayRegion(env, bytes, 0, strlen(source), (jbyte *) source);
    jstring encoding = (*env)->NewStringUTF(env, "utf-8");
    return (jstring) (*env)->NewObject(env, strClass, ctorID, bytes, encoding);
}

jstring splitJstring(JNIEnv *env, jstring source, jstring regx) {
    jclass strClass = (*env)->FindClass(env, "java/lang/String");
    jmethodID ctorID = (*env)->GetMethodID(env, strClass, "split", "(Ljava/lang/String;)[Ljava/lang/String;");
    jobjectArray array = (jobjectArray) (*env)->CallObjectMethod(env, source, ctorID, regx);
    jstring key = (jstring) (*env)->GetObjectArrayElement(env, array, 1);
    return key;
}

